package com.example.cofeed.activity.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import  com.example.cofeed.util.ToastUtils;;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.cofeed.R;
import com.example.cofeed.activity.AttentionMoreActivity;
import com.example.cofeed.activity.DetailsActivity;
import com.example.cofeed.activity.MyMsgActivity;
import com.example.cofeed.activity.MySubscriptionActivity;
import com.example.cofeed.activity.OnLineSubscibeActivity;
import com.example.cofeed.activity.PushSubscriptionActivity;
import com.example.cofeed.adapter.AttentionBreedAdapter;
import com.example.cofeed.adapter.DateSelectAdapter;
import com.example.cofeed.adapter.NoteAdapter;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.base.BaseFragment;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.constant.SputilsConstant;
import com.example.cofeed.entity.Catalogs;
import com.example.cofeed.entity.Home;
import com.example.cofeed.entity.Msg;
import com.example.cofeed.even.HomeRefreshEven;
import com.example.cofeed.even.LoginEeven;
import com.example.cofeed.even.RefreshEven;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class MsgFragment extends BaseFragment {
    @BindView(R.id.play_tv)
    TextView playTv;
    @BindView(R.id.breed_tv)
    TextView mBreedTv;
    @BindView(R.id.breed_category_tv)
    TextView mBreedCategoryTv;
    @BindView(R.id.date_tv)
    TextView mDateTv;
    @BindView(R.id.rv_list)
    RecyclerView mRvList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    private NoteAdapter mNoteAdapter;

    private List<Catalogs> catalogsList = new ArrayList<>();
    private ArrayList<String> selectBreedList = new ArrayList<>();
    private String catalogid = "0";
    private String title = "";
    private AttentionBreedAdapter attentionBreedAdapter;

    private SpeechSynthesizer mTts;
    private String mAutoToken;


    @Override
    protected boolean isBindEventBus() {
        return true;
    }

    @Override
    protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_msg, container, false);
        return view;
    }

    @Override
    protected void initData() {
        mRvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mNoteAdapter = new NoteAdapter();
        mRvList.setAdapter(mNoteAdapter);

        mRefreshLayout.setEnableLoadMore(false);

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getData();
            }
        });
        mNoteAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            Msg msg = (Msg) adapter.getData().get(position);
            Intent intent = new Intent(getActivity(), DetailsActivity.class);
            intent.putExtra(IntentKeyConstant.MSG_ID, msg.smsid);
            startActivity(intent);
        });

        mTts = SpeechSynthesizer.createSynthesizer(getActivity(), mTtsInitListener);

        initDataToken();
    }

    private void initDataToken(){
        View inflate = getActivity().getLayoutInflater().inflate(R.layout.include_guanzhu_empty, (ViewGroup) mRvList.getParent(), false);
        TextView guanzhu = inflate.findViewById(R.id.tv_goguanzhu);
        TextView title = inflate.findViewById(R.id.tv_title);

        mAutoToken = SPUtils.getInstance().getString(SputilsConstant.AUTO_TOKEN);
        if (ObjectUtils.isNotEmpty(mAutoToken)) {
            if (isCanDo()) {
                mRefreshLayout.setEnableRefresh(true);
                getData();
            } else {
                mNoteAdapter.setEmptyView(inflate);
                mRefreshLayout.setEnableRefresh(false);

                switch (mAutoToken) {
                    case "no_opened":
                        title.setText("暂未开通短信服务，请联系客服开通！");
                        guanzhu.setText("拨打电话");
                        guanzhu.setOnClickListener(v -> {
                            ApiService.service_phone(this, new DialogCallback<LzyResponse<Map<String, String>>>(getActivity()) {
                                @Override
                                public void onSuccess(Response<LzyResponse<Map<String, String>>> response) {
                                    String tel = response.body().data.get("tel");
                                    PhoneUtils.dial(tel);

                                }
                            });
                        });
                        break;
                    case "service_closed":
                        title.setText("短信服务到期，点击拨打电话开通！");
                        guanzhu.setText("拨打电话");
                        guanzhu.setOnClickListener(v -> {
                            ApiService.service_phone(this, new DialogCallback<LzyResponse<Map<String, String>>>(getActivity()) {
                                @Override
                                public void onSuccess(Response<LzyResponse<Map<String, String>>> response) {
                                    String tel = response.body().data.get("tel");
                                    PhoneUtils.call(tel);

                                }
                            });
                        });
                        break;
                    case "has_binding":
                        title.setText("已在其它设备登录，请先退出！");
                        guanzhu.setVisibility(View.GONE);

                        break;
                }
            }
        }
    }

    private void getData() {
        ApiService.sms(this, selectBreedList, currentDate, "", new DialogCallback<LzyResponse<Home>>(getActivity()) {
            @Override
            public void onSuccess(Response<LzyResponse<Home>> response) {
//                if (ObjectUtils.isEmpty(response.body().data.tag)) {
//                    mBreedCategoryTv.setVisibility(View.GONE);
//                } else {
//                    mBreedCategoryTv.setVisibility(View.VISIBLE);
//                }
//                mBreedCategoryTv.setText(response.body().data.sysmsg);
                if (ObjectUtils.isEmpty(mNoteAdapter.getData())) {
                    View view = getActivity().getLayoutInflater().inflate(R.layout.include_no_data, null);
                    mNoteAdapter.setEmptyView(view);
                }
                mNoteAdapter.setNewData(response.body().data.messagelist);
//                mRvList.scrollToPosition(0);
                mRvList.smoothScrollToPosition(0);

                initPlayButton();

                finishRefresh(mRefreshLayout);

            }

            @Override
            public void onError(Response<LzyResponse<Home>> response) {
                super.onError(response);
                finishRefresh(mRefreshLayout);

            }
        });
    }

    private boolean isCanDo() {
        if (ObjectUtils.isEmpty(mAutoToken)) {
            return false;
        }
        if (mAutoToken.equals("no_opened") || mAutoToken.equals("service_closed") || mAutoToken.equals("has_binding")) {
            return false;
        }
        return true;
    }

    @OnClick({R.id.breed_tv, R.id.layout_category, R.id.date_tv, R.id.tv_sub_title, R.id.play_tv})
    public void onViewClicked(View view) {
        if (!isCanDo()) {
            return;
        }
        switch (view.getId()) {
            case R.id.breed_tv:
                ApiService.is_subscribe(this, new DialogCallback<LzyResponse<Map<String, Integer>>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<Map<String, Integer>>> response) {
                        int status = response.body().data.get("status");
                        if (status == 1) {
                            ActivityUtils.startActivity(OnLineSubscibeActivity.class);
                        } else {
                            ToastUtils.showShort("暂未开放在线订阅");
                        }
                    }
                });
                break;
            case R.id.layout_category:
                if (ObjectUtils.isEmpty(catalogsList)) {
                    ApiService.smsCatalogs(this, new DialogCallback<LzyResponse<Catalogs>>(getActivity()) {
                        @Override
                        public void onSuccess(Response<LzyResponse<Catalogs>> response) {
                            if (!ObjectUtils.isEmpty(response.body().data.catalogs)) {
                                catalogsList.addAll(response.body().data.catalogs);
                            }
                            showBreedDialog();

                        }
                    });
                } else {
                    showBreedDialog();
                }
                break;
            case R.id.date_tv:
                showDateDialog();
                break;
            case R.id.tv_sub_title:
                ActivityUtils.startActivity(MyMsgActivity.class);
                break;
            case R.id.play_tv:
                switch (playing) {
                    case -1://第一次播放
//                        StringBuffer stringBuffer = new StringBuffer();
//                        for (Msg msg:mNoteAdapter.getData()) {
//                            stringBuffer.append(msg.content);
//                        }

//                        playVoice(stringBuffer.toString());
                        playVoice(mNoteAdapter.getData().get(currentPlayPage).content);
                        if (ObjectUtils.isEmpty(mNoteAdapter.getData().get(currentPlayPage).content)) {
                            return;
                        }
                        playTv.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.sy_yuyin_zanting), null,
                                null, null);
                        break;
                    case 0://暂停后播放
                        playTv.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.sy_yuyin_zanting), null,
                                null, null);
                        mTts.resumeSpeaking();
                        playing = 1;
                        break;
                    case 1://暂停
                        playTv.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.sy_yuyin), null,
                                null, null);
                        mTts.pauseSpeaking();
                        playing = 0;
                        break;
                    case 2://播放完成
                        StringBuffer stringBufferReplay = new StringBuffer();
                        for (Msg msg : mNoteAdapter.getData()) {
                            stringBufferReplay.append(msg.content);
                        }
                        playVoice(stringBufferReplay.toString());
                        break;
                    default:
                }
                break;
            default:
        }
    }

    private int currentPlayPage = 0;

    List<String> breeds = new ArrayList<>();
    private Dialog mDialog;
    private int selectDatePosition;
    private String currentDate = "";

    private void showDateDialog() {
        if (mDialog == null) {
            mDialog = new Dialog(getActivity(), R.style.CustomDialog);
            View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date_select, null, false);
            inflate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mDialog.dismiss();
                }
            });
            RecyclerView rvList = (RecyclerView) inflate.findViewById(R.id.rec_lv);
            mDialog.setContentView(inflate);
            mDialog.setCanceledOnTouchOutside(true);
            mDialog.setCancelable(true);
            inflate.findViewById(R.id.confirm_tv).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (selectDatePosition == 0) {
                        mDateTv.setText("日期选择");
                    } else {
                        mDateTv.setText(breeds.get(selectDatePosition));
                    }
                    mDialog.dismiss();
                    getData();
                }
            });

            rvList.setLayoutManager(new GridLayoutManager(getActivity(), 6));
            final DateSelectAdapter dateSelectAdapter = new DateSelectAdapter();
            rvList.setAdapter(dateSelectAdapter);

            dateSelectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    selectDatePosition = position;
                    Calendar c = Calendar.getInstance();
//                    granaryAdapter.setAllShow(false);
                    switch (position) {
                        case 0:
//                            granaryAdapter.setAllShow(true);
                            currentDate = "";
                            break;
                        case 1:
                            currentDate = TimeUtils.date2String(c.getTime(), new SimpleDateFormat("yyyy-MM-dd"));
                            break;
                        case 2:
                            c.set(Calendar.DATE, c.get(Calendar.DATE) - 1);
                            currentDate = TimeUtils.date2String(c.getTime(), new SimpleDateFormat("yyyy-MM-dd"));
                            break;
                        case 3:
                            c.set(Calendar.DATE, c.get(Calendar.DATE) - 2);
                            currentDate = TimeUtils.date2String(c.getTime(), new SimpleDateFormat("yyyy-MM-dd"));
                            break;
                        case 4:
                            c.set(Calendar.DATE, c.get(Calendar.DATE) - 3);
                            currentDate = TimeUtils.date2String(c.getTime(), new SimpleDateFormat("yyyy-MM-dd"));
                            break;
                        case 5:
                            c.set(Calendar.DATE, c.get(Calendar.DATE) - 4);
                            currentDate = TimeUtils.date2String(c.getTime(), new SimpleDateFormat("yyyy-MM-dd"));
                            break;
                    }
                    dateSelectAdapter.setSelect(position);

                }
            });

            if (ObjectUtils.isEmpty(breeds)) {
                breeds.add("全部");

                Calendar c = Calendar.getInstance();//
                int mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
                int mDay = c.get(Calendar.DAY_OF_MONTH);// 获取当日期

                breeds.add(mMonth + "." + mDay);

                c.set(Calendar.DATE, c.get(Calendar.DATE) - 1);
                int mMonth1 = c.get(Calendar.MONTH) + 1;// 获取当前月份
                int mDay1 = c.get(Calendar.DAY_OF_MONTH);// 获取当日期
                breeds.add(mMonth1 + "." + mDay1);

                c.set(Calendar.DATE, c.get(Calendar.DATE) - 1);
                int mMonth2 = c.get(Calendar.MONTH) + 1;// 获取当前月份
                int mDay2 = c.get(Calendar.DAY_OF_MONTH);// 获取当日期
                breeds.add(mMonth2 + "." + mDay2);

                c.set(Calendar.DATE, c.get(Calendar.DATE) - 1);
                int mMonth3 = c.get(Calendar.MONTH) + 1;// 获取当前月份
                int mDay3 = c.get(Calendar.DAY_OF_MONTH);// 获取当日期
                breeds.add(mMonth3 + "." + mDay3);

                c.set(Calendar.DATE, c.get(Calendar.DATE) - 1);
                int mMonth4 = c.get(Calendar.MONTH) + 1;// 获取当前月份
                int mDay4 = c.get(Calendar.DAY_OF_MONTH);// 获取当日期
                breeds.add(mMonth4 + "." + mDay4);

                dateSelectAdapter.setNewData(breeds);
                dateSelectAdapter.setSelect(0);
            }

            Window localWindow = mDialog.getWindow();
            localWindow.setWindowAnimations(R.style.dialog_animation);
            localWindow.setGravity(Gravity.CENTER);
            localWindow.setBackgroundDrawableResource(android.R.color.transparent);
            localWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        }

        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
        }

    }


    private void showBreedDialog() {
        final Dialog mDialog = new Dialog(getActivity(), R.style.CustomDialog);
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_breed_select, null, false);
        inflate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
            }
        });
        inflate.findViewById(R.id.subscription_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtils.startActivity(MySubscriptionActivity.class);
            }
        });
        RecyclerView rvList = (RecyclerView) inflate.findViewById(R.id.rec_lv);
        mDialog.setContentView(inflate);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.setCancelable(true);
        inflate.findViewById(R.id.confirm_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ObjectUtils.isEmpty(catalogid)) {
                    return;
                }
                selectBreedList.clear();
                selectBreedList.add(catalogid);
                mBreedCategoryTv.setText(title);
                mDialog.dismiss();
                getData();


            }
        });

        rvList.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        attentionBreedAdapter = new AttentionBreedAdapter();
        rvList.setAdapter(attentionBreedAdapter);

        attentionBreedAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Catalogs catalogs = (Catalogs) adapter.getItem(position);
                if (ObjectUtils.isEmpty(catalogs.catalogid)) {
//                    EventBus.getDefault().post(new TabEven());
                    mDialog.dismiss();
                } else {
                    catalogid = catalogs.catalogid;
                    title = catalogs.title;
                    attentionBreedAdapter.setSingleSelect(catalogs);

                    selectBreedList.clear();
                    selectBreedList.add(catalogid);
                    mBreedCategoryTv.setText(title);
                    mDialog.dismiss();
                    getData();


                }


            }
        });
        attentionBreedAdapter.setNewData(catalogsList);
        Window localWindow = mDialog.getWindow();
        localWindow.setWindowAnimations(R.style.dialog_animation);
        localWindow.setGravity(Gravity.CENTER);
        localWindow.setBackgroundDrawableResource(android.R.color.transparent);
        localWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(HomeRefreshEven homeRefreshEven) {
        mNoteAdapter.notifyDataSetChanged();

    }

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
//            Log.d(TAG, "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                ToastUtils.showShort("初始化失败,错误码：" + code);
            } else {
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };
    int playing = -1;

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
        }

        @Override
        public void onSpeakPaused() {
            playing = 0;

        }

        @Override
        public void onSpeakResumed() {
            playing = 1;

        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
            // 合成进度
//            mPercentForBuffering = percent;

        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
//            mPercentForPlaying = percent;

        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
//                showTip("播放完成");
                currentPlayPage++;
                if (!ObjectUtils.isEmpty(mNoteAdapter.getData().get(currentPlayPage).content)) {
                    playVoice(mNoteAdapter.getData().get(currentPlayPage).content);
                    return;
                }
                playing = 2;
                playTv.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.sy_yuyin), null,
                        null, null);
            } else if (error != null) {
                ToastUtils.showShort(error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    void initPlayButton() {
        mTts.stopSpeaking();
        playing = -1;
        currentPlayPage = 0;
        playTv.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.sy_yuyin), null,
                null, null);
    }

    void playVoice(String user_input) {
        if (ObjectUtils.isEmpty(user_input)) {
            ToastUtils.showShort("暂无内容！");
            return;
        }
        int code = mTts.startSpeaking(user_input, mTtsListener);
        if (code != ErrorCode.SUCCESS) {
            ToastUtils.showShort("语音合成失败,错误码: " + code);
        } else {
            playing = 1;
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mTts) {
            mTts.stopSpeaking();
            // 退出时释放连接
            mTts.destroy();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(RefreshEven refreshEven) {
        if (refreshEven.type == 2) {
            mRefreshLayout.autoRefresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Login(LoginEeven loginEeven) {
        if (mNoteAdapter == null) {
            return;
        }
        initDataToken();
        if (isCanDo()){
            mRefreshLayout.autoRefresh();

        }

    }
}
